#ifndef CUSTOM_RC_POST_INCLUDED
#define CUSTOM_RC_POST_INCLUDED

#include "Common.hlsl"

uniform Texture2D _BlueNoiseTex;
SamplerState sampler_BlueNoiseTex;

float4 RayMarching(in float2 InPos, in float2 InDir)
{
    float t = 0.;
    
    for (int MarchingStep = 0; MarchingStep < 10; MarchingStep++)
    {
        float4 SdfResult = Global_Sdf(InPos + t * InDir);
        if (SdfResult.w < 0.01)
        {
            return float4(SdfResult.rgb, 1.0);
        }
        t += SdfResult.w;
        if (t > 4.)
            break;
    }

    return float4(0.0, 0.0, 0.0, 0.0);
}

float3 Radiance(in float2 InPos, in float Noise)
{
    int RayCount = 512;
    float InvRayCount = 1.0 / float(RayCount);
    
    float3 Result = float3(0.0, 0.0, 0.0);
    const float NoiseFluence = 8.0f;
    
    for (int i = 0; i < RayCount; i++)
    {
        float StandardAngle = float(i) * InvRayCount;
    
        float Angle = (StandardAngle + (Noise * NoiseFluence * 2.0 - NoiseFluence) * InvRayCount) * 2.0 * 3.14159;
        float2 Dir = float2(sin(Angle), cos(Angle));
        
        Result += RayMarching(InPos, Dir).rgb;
    }
    return Result / float(RayCount);
}

float4 RadianceCascadesFragment(Varyings input) : SV_TARGET
{
    // input.texcoord                       in [0, 1]       x [0, 1]
    // (input.texcoord - 0.5) * 2.0         in [-1, 1]      x [-1, 1]
    // uv                                   in [-x/y, x/y]  x [-1, 1]
    float2 uv = input.texcoord * _ScreenParams.xy / _ScreenParams.y;
    
    float2 NoiseUV = input.texcoord;
    // float2  = texture(iChannel0, noise_uv).xy;
    float Noise = _BlueNoiseTex.Sample(sampler_BlueNoiseTex, NoiseUV).x;
    
    float3 color = Radiance(uv, Noise);
  
    //color = ACESFitted(color);
    //color = linear_srgb(color);
    
    float4 Result = float4(color, 1.0);
    
    return Result;
}
#endif